package cn.corgy.registry.nacos;

import cn.corgy.dto.RpcRequest;
import cn.corgy.extension.ExtensionLoader;
import cn.corgy.module.loadbalance.LoadBalance;
import cn.corgy.registry.ServiceDiscovery;
import cn.corgy.registry.nacos.utils.NacosUtil;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class NacosServiceDiscovery implements ServiceDiscovery {
    private final LoadBalance loadBalance;

    public NacosServiceDiscovery() {
        this.loadBalance = ExtensionLoader.getExtensionLoader(LoadBalance.class).getExtension("loadBalance");
    }

    @Override
    public InetSocketAddress lookupService(RpcRequest rpcRequest) {
        String rpcServiceName = rpcRequest.getRpcServiceName();
        NamingService nacosClient = NacosUtil.getNacosClient();
        List<String> list = null;
        try {
            List<Instance> allInstance = NacosUtil.getAllInstance(nacosClient, rpcServiceName);
            list = allInstance.stream().map(x -> {
                return x.getIp() + ":" + x.getPort();
            }).collect(Collectors.toList());
        } catch (NacosException e) {
            e.printStackTrace();
        }
        // 负载均衡 默认配置为一致性哈希
        return getInetSocketAddress(rpcRequest, list, loadBalance, log);
    }


}
